package com.example.springboot.service.impl;

import cn.hutool.core.lang.Dict;
import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.Page;
import com.example.springboot.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 商品表(Product)表服务实现类
 *
 * @author makejava
 * @since 2024-01-13 17:16:26
 */
@Service("productService")
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 测试
     *
     * @return
     */
    @Override
    public List<Product> test() {
        try {
            List<Product> test = productMapper.test();
            for (Product product : test) {
                System.out.println(product);
                System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
            }
            System.out.println("test");
            return test;
        } catch (Exception e) {
            throw new ServiceException("测试失败！");
        }
    }


    /**
     * 获取所有用户信息
     *
     * @return
     */
    @Override
    public List<Product> selectAll() {
        return productMapper.selectAll();
    }

    /**
     * 根据ID删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        try {
            productMapper.deleteById(id);
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }


    /**
     * 根据ID更新信息
     *
     * @param product
     */
    @Override
    public void updateById(Product product) {
        try {
            productMapper.updateById(product);
        } catch (Exception e) {
            throw new ServiceException("更新失败");
        }
    }

    /**
     * 条件查询
     *
     * @param name
     * @param storeName
     * @param categoryName
     * @param status
     * @return
     */
    @Override
    public List<Product> selectByManyCondition(String name, String storeName, String categoryName, Integer status) {
        try {
            return productMapper.selectByManyCondition(name, storeName, categoryName, status);
        } catch (Exception e) {
            throw new ServiceException("查询失败");
        }
    }

    /**
     * 分页查询
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public Page<Product> selectByPage(Integer currentPage, Integer pageSize) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询总记录数
            int totalCount = productMapper.selectAll().size();
            // 查询分页数据
            List<Product> users = productMapper.selectByPage(startRow, pageSize);

            // 封装返回结果
            Page<Product> page = new Page<>();
            page.setList(users);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("分页查询失败！");
        }

    }

    /**
     * 分页查询 条件查询
     *
     * @param currentPage
     * @param pageSize
     * @param name
     * @param storeName
     * @param categoryName
     * @param status
     * @return
     */
    @Override
    public Page<Product> selectByManyConditionInpage(Integer currentPage, Integer pageSize, String name, String storeName, String categoryName, Integer status) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询总记录数
            int totalCount = productMapper.selectByManyCondition(name, storeName, categoryName, status).size();
            // 查询分页数据
            List<Product> users = productMapper.selectByManyConditionInpage(startRow, pageSize, name, storeName, categoryName, status);

            // 封装返回结果
            Page<Product> page = new Page<>();
            page.setList(users);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("条件查询失败！");
        }

    }

    /**
     * 分页查询 条件查询
     *
     * @param currentPage
     * @param pageSize
     * @param name
     * @param storeName
     * @param categoryName
     * @return
     */
    @Override
    public Page<Product> selectByManyConditionNoStatusInpage(Integer currentPage, Integer pageSize, String name, String storeName, String categoryName) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 查询总记录数
            int totalCount = productMapper.selectByManyConditionNoStatus(name, storeName, categoryName).size();
            // 查询分页数据
            List<Product> users = productMapper.selectByManyConditionNoStatusInpage(startRow, pageSize, name, storeName, categoryName);

            // 封装返回结果
            Page<Product> page = new Page<>();
            page.setList(users);
            page.setTotal(totalCount);
            return page;
        } catch (ServiceException e) {
            throw new ServiceException("条件查询失败！");
        }

    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        try {
            for (Integer id : ids) {
                productMapper.deleteById(id);
            }
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }

    /**
     * 添加商品
     *
     * @param product
     */
    @Override
    public void addProduct(Product product) {

        Store store = null;
        try {
            // 先查询商家是否存在
            store = storeMapper.selectSimpleById(product.getStoreId());
        } catch (ServiceException e) {
            throw new ServiceException("查询商家失败！");
        }
        if (store == null) {
            throw new ServiceException("商家不存在！");
        }

        Category category = null;
        try {
            // 先查询商品分类是否存在
            category = categoryMapper.selectById(product.getCategoryId());
        } catch (ServiceException e) {
            throw new ServiceException("查询商品分类失败！");
        }
        if (category == null) {
            throw new ServiceException("商品分类不存在！");
        }

//        Product productDB = null;
//        try {
//            // 先查询商品是否存在
//            productDB = productMapper.selectById(product.getId());
//        } catch (ServiceException e) {
//            throw new ServiceException("查询商品失败！");
//        }


//        if (productDB == null) {
//
//        } else {
//            //  商品存在，抛出异常
//            throw new ServiceException("商品已存在");
//        }
        try {
            productMapper.addProduct(product);
        } catch (ServiceException e) {
            throw new ServiceException("添加失败");
        }


    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Product selectById(Integer id) {
        try {
            return productMapper.selectById(id);
        } catch (Exception e) {
            throw new ServiceException("商品不存在");
        }

    }

    /**
     * 根据分类ID获取该分类下的商品数量
     *
     * @param id
     * @return
     */
    @Override
    public BigDecimal selectProductCountByCategoryId(Integer id) {
        try {
            int i = productMapper.selectProductCountByCategoryId(id);
            BigDecimal count = new BigDecimal(i);
            return count;
        } catch (Exception e) {
            throw new ServiceException("查询商品数量失败");
        }
    }

    @Override
    public List<Product> selectTop10CategoryStore(Integer id) {
        try {
            // 通过productService获取销量前20的商品集合products
            return productMapper.selectTop10CategoryStore(id);
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    /**
     * 获取Top20的商品集合
     *
     * @return
     */
    @Override
    public List<Product> selectTop10CategoryAdmin() {
        try {
            // 通过productService获取销量前20的商品集合products
            return productMapper.selectTop10CategoryAdmin();
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    /**
     * 获取商品数量
     *
     * @return
     */
    @Override
    public long getTotal() {
        try {
            return productMapper.getTotal();
        } catch (Exception e) {
            throw new ServiceException("查询商品数量失败");
        }
    }

    @Override
    public List<Product> selectByProductIds(Integer currentPage, Integer pageSize, Integer[] productIdArray) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            return productMapper.selectByProductIds(startRow, pageSize, productIdArray);
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    @Override
    public Page<Product> loadStoreProducts(Integer currentPage, Integer pageSize, Integer id) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;
            List<Product> products = productMapper.loadStoreProducts(startRow, pageSize, id);
            int total = productMapper.getStoreProductsTotal(id);
            Page<Product> page = new Page<>();
            page.setList(products);
            page.setTotal(total);
            return page;
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    @Override
    public int getUserFavoriteProductCount(Integer[] productIdsArray) {
        return productMapper.getUserFavoriteProductCount(productIdsArray);
    }

    @Override
    public int getStoreTotal(Integer id) {
        try {
            return productMapper.getStoreTotal(id);
        } catch (Exception e) {
            throw new ServiceException("查询商品总数失败");
        }
    }

    @Override
    public Page<Product> selectByPageInStore(Integer currentPage, Integer pageSize, Integer id) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;
            List<Product> products = productMapper.selectByPageInStore(startRow, pageSize, id);
            int total = productMapper.getStoreTotal(id);
            Page<Product> page = new Page<>();
            page.setList(products);
            page.setTotal(total);
            return page;
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }

    }

    @Override
    public Dict mainProducts() {
        try {
            List<Product> allProducts = productMapper.selectAllSimple(); // 获取所有商品
            List<Product> recommendedProducts = new ArrayList<>();
            List<Product> randomProducts = new ArrayList<>();
            Random random = new Random();
            Dict mainProducts = Dict.create();

            if (allProducts.size() <= 3) {
                mainProducts.set("recommendedProducts", allProducts)
                        .set("randomProducts", allProducts);
                return mainProducts;
            }

            while (recommendedProducts.size() < 3) {
                Product randomProduct = allProducts.get(random.nextInt(allProducts.size())); // 从所有商品中随机选取一个商品
                if (!recommendedProducts.contains(randomProduct)) {
                    recommendedProducts.add(randomProduct);
                }
            }

            if (allProducts.size() <= 16) {
                mainProducts.set("recommendedProducts", recommendedProducts)
                        .set("randomProducts", allProducts);
                return mainProducts;
            }


            while (randomProducts.size() < 16) {
                Product randomProduct = allProducts.get(random.nextInt(allProducts.size())); // 从所有商品中随机选取一个商品
                if (!randomProducts.contains(randomProduct)) {
                    randomProducts.add(randomProduct);
                }
            }

            mainProducts.set("recommendedProducts", recommendedProducts)
                    .set("randomProducts", randomProducts);
            return mainProducts;
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    @Override
    public List<Product> getRecommendedProducts() {
        try {
            List<Product> allProducts = productMapper.selectAllSimple(); // 获取所有商品

            List<Product> selectedProducts = new ArrayList<>();
            Random random = new Random();

            if (allProducts.size() <= 16) {
                return allProducts; // 如果商品数量不足16个，直接返回所有商品
            }

            while (selectedProducts.size() < 16) {
                Product randomProduct = allProducts.get(random.nextInt(allProducts.size())); // 从所有商品中随机选取一个商品
                if (!selectedProducts.contains(randomProduct)) {
                    selectedProducts.add(randomProduct);
                }
            }
            return selectedProducts;
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    @Override
    public List<Product> getRandomProducts(Integer size) {
        try {
            List<Product> allProducts = productMapper.selectAllSimple(); // 获取所有商品

            List<Product> selectedProducts = new ArrayList<>();
            Random random = new Random();

            if (allProducts.size() <= size) {
                return allProducts;
            }

            while (selectedProducts.size() < size) {
                Product randomProduct = allProducts.get(random.nextInt(allProducts.size())); // 从所有商品中随机选取一个商品
                if (!selectedProducts.contains(randomProduct)) {
                    selectedProducts.add(randomProduct);
                }
            }
            return selectedProducts;
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    @Override
    public Page<Product> selectByCategory(Integer currentPage, Integer pageSize, Integer id) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;
            List<Product> products1 = productMapper.selectByCategory(id);
            List<Product> products = productMapper.selectByCategoryInPage(startRow, pageSize, id);
            Page<Product> page = new Page<>();
            page.setTotal(products1.size());
            page.setList(products);
            return page;
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    @Override
    public Page<Product> selectByCondition(Integer currentPage, Integer pageSize, String condition) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;
            List<Product> products1 = productMapper.selectByCondition(condition);

            List<Product> products = productMapper.selectByConditionInPage(startRow, pageSize, condition);

            Page<Product> page = new Page<>();
            page.setTotal(products1.size());
            page.setList(products);
            return page;
        } catch (Exception e) {
            throw new ServiceException("查询商品失败");
        }
    }

    @Override
    public List<Product> loadStoreNewProducts(Integer id) {
        try {
            List<Product> products = productMapper.selectByStoreId(id);
            // 过滤出状态为1的商品集合
            products = products.stream().filter(product -> product.getStatus() == 1).distinct().collect(Collectors.toList());
            // 根据商品的createTime进行排序
            products.sort(Comparator.comparing(Product::getCreateTime).reversed());
            // 截取8个商品
            if (products.size() > 4) {
                products = products.subList(0, 4);
            }
            return products;
        } catch (Exception e) {
            throw new ServiceException("加载店铺新品失败");
        }
    }

    @Override
    public List<Product> loadRecommendedProducts(Integer id) {
        try {

            List<Product> allProducts = productMapper.selectByStoreId(id); // 获取所有商品
            allProducts = allProducts.stream().filter(product -> product.getStatus() == 1).distinct().collect(Collectors.toList());
            List<Product> recommendedProducts = new ArrayList<>();
            Random random = new Random();

            if (allProducts.size() <= 4) {
                return allProducts;
            }
            while (recommendedProducts.size() < 4) {
                Product randomProduct = allProducts.get(random.nextInt(allProducts.size())); // 从所有商品中随机选取一个商品
                if (!recommendedProducts.contains(randomProduct)) {
                    recommendedProducts.add(randomProduct);
                }
            }
            return recommendedProducts;
        } catch (Exception e) {
            throw new ServiceException("加载推荐商品失败");
        }
    }

    @Override
    public void update(Product product) {
        try {
            productMapper.update(product);
        } catch (Exception e) {
            throw new ServiceException("更新商品信息失败");
        }
    }


}
